package sy.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sy.model.TQuiz;
import sy.model.TQuizManager;
import sy.model.Tuser;
import sy.pageModel.DataGrid;
import sy.pageModel.Json;
import sy.pageModel.PageHelper;
import sy.pageModel.QuizModel;
import sy.service.QuizManagerServiceI;
import sy.service.QuizServiceI;
import sy.service.UserServiceI;
import sy.util.DateCompare;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//竞猜
@Controller
@RequestMapping("/quizController")
public class QuizController extends BaseController {
	@Autowired
	private QuizServiceI quizService;
	@Autowired
	private QuizManagerServiceI quizManagerService;

    @Autowired
    private UserServiceI userService;

	//获得竞猜信息
		@RequestMapping("/getquizinfo")
		@ResponseBody
		public Json getquizinfo(HttpServletResponse response,HttpServletRequest request, HttpSession session) {
			Json j = new Json();
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            String userid=request.getParameter("userid");
         	try {
				
				TQuizManager quiz=quizManagerService.getLastTQuizManager();
				
				//页面model
				QuizModel quizModel=new QuizModel();
			
				Date overtime;
				long endtime;
				long todaytime;
				
				if(quiz!=null){
					
					endtime=format.parse(quiz.getEndtime()).getTime();
					todaytime=new Date().getTime();
					
					if(DateCompare.compare_date(format.format(new Date()),quiz.getEndtime())>0){//竞猜结束
						quizModel.setIsquiz(0);
						quizModel.setEndtime("已结束");
					}else{
						quizModel.setIsquiz(1);
						overtime=new Date(endtime-todaytime);
						//当前轮信息
						quizModel.setEndtime(overtime.getHours()+":"+overtime.getMinutes());
					}
					quizModel.setGold(quiz.getGold());
					
					//查询这一期多少人参加
					int periodnumbersize=quizService.getPeriodnumber(quiz.getPeriodnumber());
					quizModel.setPersoncount(periodnumbersize+"");
					
					//设置期号
					quizModel.setPeriodnumber(quiz.getPeriodnumber());
				}
			
				//设置上一轮信息
				TQuizManager lastlast=quizManagerService.getLastAfterTQuizManager();
				if(lastlast!=null){
					quizModel.setNumber(lastlast.getNumber());
					quizModel.setLastgold(lastlast.getGold());
					
					//获得上一轮中奖用户ids和统计总数
					List<TQuiz> quizs=quizService.getQuizByPN(lastlast.getPeriodnumber(), lastlast.getNumber());
					String getgolds="";
					for(TQuiz tQuiz :quizs){
						getgolds+=tQuiz.getUserid()+",";
					}
					if(!"".equals(getgolds)){
						
						getgolds=	getgolds.substring(0,getgolds.lastIndexOf(",") );
						
					}
					quizModel.setGetgolds(getgolds);
					
					quizModel.setLastperson(lastlast.getGold()+"("+quizs.size()+"人平分)");
					
				}
                Map<Object, Object> map=new HashMap<Object, Object>();
                map.put("userid",userid);
                map.put("quizModel",quizModel);
				//j.setObj(user.getUserid());
				//j.setObj("quizModel");
                j.setObj(map);
				j.setMsg("获取成功！");
				j.setSuccess(true);
			} catch (Exception e) {
				j.setMsg("获取失败！");
				j.setSuccess(false);
				e.printStackTrace();
			}
			return j;
		}
	
		//竞猜
	@RequestMapping("/quiz")
	@ResponseBody
	public String quiz(HttpSession session, HttpServletResponse response,HttpServletRequest request){
		response.setCharacterEncoding("utf-8");
		String userid=request.getParameter("userid");
		Tuser user=userService.getUserByUserId(userid);
        String rs="";
        if(user==null){
            rs="请重新登陆";
        }else{
            String number=request.getParameter("number");
            String periodnumber=request.getParameter("periodnumber");
            JSONObject jsobj =new JSONObject();
            TQuiz quiz=new TQuiz();
            //是否竞猜 在一天内是否有过竞猜 记录日期
            Date date=new Date();
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            String createdatetime=format.format(date);
            List<TQuiz> quizs=quizService.getQuiz(user.getUserid()+"", createdatetime);

            if(quizs.size()>0){
                //已经竞猜 当天不能再竞猜
                rs="当天不能重复竞猜";
            }else{

                try {
                    quiz.setPeriodnumber(periodnumber);
                    quiz.setNumber(number);
                    quiz.setUserid(user.getUserid()+"");
                    quiz.setCreatedatetime(createdatetime);
                    quiz.setStatus(-1);//-1 : 未开奖  0:开奖 1:开奖
                    quizService.add(quiz);
                    rs="竞猜成功";

                } catch (Exception e) {
                    rs="竞猜失败";

                }
            }
        }

		return rs;
	}
	
	@RequestMapping("/dataGrid")
	@ResponseBody
	public DataGrid dataGrid(TQuiz tad, PageHelper ph) {
		return quizService.dataGrid(tad, ph);
	}
	
	/**
	 * 跳转到用户管理页面
	 * 
	 * @return
	 */
	@RequestMapping("/manager")
	public String manager() {
		return "/quiz/index";
	}
	
	
}
